package com.enki.cigarettes.controller;

import com.enki.cigarettes.controller.vo.request.DeliverAddressRequestVo;
import com.enki.cigarettes.entity.DeliverAddressT;
import com.enki.cigarettes.handler.Response;
import com.enki.cigarettes.repository.DeliverAddressTRepository;
import com.enki.cigarettes.statics.StaticKeys;
import com.enki.cigarettes.utils.PrimaryKey;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.controller
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 用户地址逻辑层
 * @date 2019-07-19
 */
@RestController
@RequestMapping("/api/addresses")
@Slf4j
public class DeliverAddressController {

    @Autowired
    DeliverAddressTRepository deliverAddressTRepository;

    @ApiOperation(value = "保存地址")
    @PostMapping
    @Transactional
    public Object saveAddress(@RequestBody DeliverAddressRequestVo item, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            if (StringUtils.isBlank(item.getContacts())) {
                return Response.badRequest_400("请输入联系人");
            }
            if (StringUtils.isBlank(item.getPhone())) {
                return Response.badRequest_400("请输入手机号");
            }
            // 联系人手机号码验证
            String phoneRegex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
            if (!item.getPhone().matches(phoneRegex)) {
                return Response.badRequest_400("手机号码格式不正确");
            }
            if (StringUtils.isBlank(item.getProvince())) {
                return Response.badRequest_400("请输入省份");
            }
            if (StringUtils.isBlank(item.getCity())) {
                return Response.badRequest_400("请输入市区");
            }
            if (StringUtils.isBlank(item.getCounty())) {
                return Response.badRequest_400("请输入区域");
            }
            if (StringUtils.isBlank(item.getAddress())) {
                return Response.badRequest_400("请输入详细地址");
            }
            if (item.isIsDefault()) {
                DeliverAddressT bean = deliverAddressTRepository.findOneByUserTIdAndIsDefault(sessionId.toString(), true);
                if (bean != null && bean.isIsDefault()) {
                    bean.setIsDefault(false);
                    deliverAddressTRepository.save(bean);
                }
            }
            DeliverAddressT bean = new DeliverAddressT();
            BeanUtils.copyProperties(item, bean);
            bean.setId(PrimaryKey.get().toString());
            bean.setUserTId(sessionId.toString());
            bean.setCreateTime(new Date());
            deliverAddressTRepository.save(bean);
            return Response.success(bean.getId(), StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("保存用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，保存地址信息失败");
        }
    }

    @ApiOperation(value = "获取地址列表")
    @GetMapping
    public Object findAddressList(HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_CREATE_TIME);
            List<DeliverAddressT> beanList = deliverAddressTRepository.findByUserTId(sessionId.toString(), sort);
            List<DeliverAddressT> beanArr = new ArrayList<>();
            for (DeliverAddressT bean : beanList) {
                bean.setPhone(bean.getPhone().substring(0, 3) + "****" + bean.getPhone().substring(7));
                beanArr.add(bean);
            }
            return Response.success(beanArr, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("保存用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，保存地址信息失败");
        }
    }

    @ApiOperation(value = "获取地址详情")
    @ApiImplicitParam(name = "id", value = "地址ID", dataType = "long", required = true)
    @GetMapping(value = "/{id}")
    public Object findAddressById(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            DeliverAddressT bean = deliverAddressTRepository.findOneByIdAndUserTId(id, sessionId.toString());
            if (bean != null) {
                //bean.setPhone(bean.getPhone().substring(0, 3) + "****" + bean.getPhone().substring(7));
                return Response.success(bean, StaticKeys.SUCCESS);
            } else {
                return Response.notFound_404("不存在的地址信息");
            }
        } catch (Exception e) {
            log.error("获取用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，获取地址信息失败");
        }
    }

    @ApiOperation(value = "更新地址信息")
    @ApiImplicitParam(name = "id", value = "地址ID", dataType = "String", required = true)
    @PutMapping(value = "/{id}")
    @Transactional
    public Object updateAddress(@PathVariable String id, @RequestBody DeliverAddressRequestVo item, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            if (StringUtils.isBlank(item.getContacts())) {
                return Response.badRequest_400("请输入联系人");
            }
            if (StringUtils.isBlank(item.getPhone())) {
                return Response.badRequest_400("请输入手机号");
            }
            // 联系人手机号码验证
            String phoneRegex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
            if (!item.getPhone().matches(phoneRegex)) {
                return Response.badRequest_400("手机号码格式不正确");
            }
            if (StringUtils.isBlank(item.getProvince())) {
                return Response.badRequest_400("请输入省份");
            }
            if (StringUtils.isBlank(item.getCity())) {
                return Response.badRequest_400("请输入市区");
            }
            if (StringUtils.isBlank(item.getCounty())) {
                return Response.badRequest_400("请输入区域");
            }
            if (StringUtils.isBlank(item.getAddress())) {
                return Response.badRequest_400("请输入详细地址");
            }
            DeliverAddressT bean = deliverAddressTRepository.findOneByIdAndUserTId(id, sessionId.toString());
            if (bean != null) {
                if (item.isIsDefault()) {
                    DeliverAddressT defaultBean = deliverAddressTRepository.findOneByUserTIdAndIsDefault(sessionId.toString(), true);
                    if (defaultBean != null && defaultBean.isIsDefault() && !defaultBean.getId().equals(id)) {
                        defaultBean.setIsDefault(false);
                        deliverAddressTRepository.save(defaultBean);
                    }
                }
                BeanUtils.copyProperties(item, bean);
                deliverAddressTRepository.save(bean);
                return Response.success();
            } else {
                return Response.notFound_404("不存在的地址信息");
            }
        } catch (Exception e) {
            log.error("更新用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，更新地址信息失败");
        }
    }

    @ApiOperation(value = "删除地址")
    @ApiImplicitParam(name = "id", value = "地址ID", dataType = "long", required = true)
    @DeleteMapping(value = "/{id}")
    public Object delAddress(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            DeliverAddressT bean = deliverAddressTRepository.findOneByIdAndUserTId(id, sessionId.toString());
            if (bean != null) {
                deliverAddressTRepository.delete(bean);
                return Response.success();
            } else {
                return Response.notFound_404("不存在的地址信息");
            }
        } catch (Exception e) {
            log.error("删除用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，删除地址信息失败");
        }
    }

    @ApiOperation(value = "默认地址")
    @GetMapping(value = "/default")
    public Object findDefault(HttpSession session) {
        try {
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("default", false);
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            DeliverAddressT defaultBean = deliverAddressTRepository.findOneByUserTIdAndIsDefault(sessionId.toString(), true);
            if (defaultBean != null) {
                responseData.put("default", true);
                defaultBean.setPhone(defaultBean.getPhone().substring(0, 3) + "****" + defaultBean.getPhone().substring(7));
                responseData.put("defaultBean", defaultBean);
            } else {
                Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_CREATE_TIME);
                List<DeliverAddressT> beanList = deliverAddressTRepository.findByUserTId(sessionId.toString(), sort);
                if (beanList.size() > 0) {
                    responseData.put("default", true);
                    defaultBean = beanList.get(0);
                    defaultBean.setPhone(defaultBean.getPhone().substring(0, 3) + "****" + defaultBean.getPhone().substring(7));
                    responseData.put("defaultBean", defaultBean);
                }
            }
            return Response.success(responseData, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取用户默认地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，获取默认地址信息失败");
        }
    }


    @ApiOperation(value = "默认地址")
    @PutMapping(value = "/default/{id}")
    @Transactional
    public Object updateDefault(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            DeliverAddressT bean = deliverAddressTRepository.findOneByIdAndUserTId(id, sessionId.toString());
            if (bean != null) {
                DeliverAddressT defaultBean = deliverAddressTRepository.findOneByUserTIdAndIsDefault(sessionId.toString(), true);
                if (defaultBean != null && defaultBean.isIsDefault() && !defaultBean.getId().equals(id)) {
                    defaultBean.setIsDefault(false);
                    deliverAddressTRepository.save(defaultBean);
                }
                bean.setIsDefault(true);
                deliverAddressTRepository.save(bean);
                return Response.success();
            } else {
                return Response.notFound_404("不存在的地址信息");
            }
        } catch (Exception e) {
            log.error("设置默认地址失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，设置默认地址失败");
        }
    }


    @ApiOperation(value = "获取地址列表")
    @GetMapping(value = "/order")
    public Object findAddressListByOrder(HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_CREATE_TIME);
            List<DeliverAddressT> beanList = deliverAddressTRepository.findByUserTId(sessionId.toString(), sort);
            List<DeliverAddressT> beanArr = new ArrayList<>();
            for (DeliverAddressT bean : beanList) {
                bean.setPhone(bean.getPhone().substring(0, 3) + "****" + bean.getPhone().substring(7));
                bean.setAddress(bean.getContacts() + " " + bean.getPhone() + " " + bean.getProvince() + bean.getCity() + bean.getCounty() + bean.getAddress());
                beanArr.add(bean);
            }
            return Response.success(beanArr, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("保存用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，保存地址信息失败");
        }
    }

    @ApiOperation(value = "获取地址详情")
    @ApiImplicitParam(name = "id", value = "地址ID", dataType = "long", required = true)
    @GetMapping(value = "/order/{id}")
    public Object findAddressByIdForOrder(@PathVariable String id, HttpSession session) {
        try {
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("default", false);
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            DeliverAddressT bean = deliverAddressTRepository.findOneByIdAndUserTId(id, sessionId.toString());
            if (bean != null) {
                responseData.put("default", true);
                bean.setPhone(bean.getPhone().substring(0, 3) + "****" + bean.getPhone().substring(7));
                responseData.put("bean", bean);
                return Response.success(responseData, StaticKeys.SUCCESS);
            } else {
                return Response.notFound_404("不存在的地址信息");
            }
        } catch (Exception e) {
            log.error("获取用户地址信息失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，获取地址信息失败");
        }
    }


}
